package com.demo.feifan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * kafka  发送控制器
 */

@RestController
@RequestMapping("/api/kafka")
public class KafkaProducerController {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 发送测试消息到t_demo主题
     * 
     * @param key 消息的key
     * @param value 消息的value
     * @return 发送结果
     */
    @PostMapping("/send")
    public String sendMessage(
            @RequestParam String key,
            @RequestParam String value) {
        try {
            kafkaTemplate.send("t_demo", key, value);
            return "Message sent successfully: Key=" + key + ", Value=" + value;
        } catch (Exception e) {
            return "Failed to send message: " + e.getMessage();
        }
    }

    /**
     * 发送简单测试消息
     * 
     * @param message 消息内容（同时作为key和value）
     * @return 发送结果
     */
    @PostMapping("/send-simple")
    public String sendSimpleMessage(@RequestParam String message) {
        try {
            kafkaTemplate.send("t_demo", message, message);
            return "Simple message sent successfully: " + message;
        } catch (Exception e) {
            return "Failed to send message: " + e.getMessage();
        }
    }
}
